package com.sx.manage.service.consumer.company.excel;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sx.common.util.BeanUtils;
import com.sx.common.util.NumberUtil;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.manage.biz.consumer.info.IMNetworkPersonConsumerBiz;
import com.sx.manage.service.consumer.company.excel.consumer.IMcompanyImportConsumerInfoService;
import com.sx.manage.service.consumer.info.IMConsumerOperationInfoService;
import com.sx.manage.service.consumer.network.IMBasePersonConsumerNetworkService;
import com.sx.manage.service.consumer.util.MConsumerWebServiceUtil;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.model.constants.MPaperTypeUtil;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.bank.MUserInfoBankValidate;
import com.sx.model.constants.type.consumer.MCompanyConsumersImportStatus;
import com.sx.model.exception.MRollbackException;
import com.sx.model.manage.mybatis.form.company.MCompanyImportConsumerInfoForm;
import com.sx.model.manage.mybatis.form.consumer.MPersonalConsumerNetworkForm;
import com.sx.model.manage.mybatis.form.sys.MSystemConfigInfoForm;
import com.sx.model.manage.mybatis.vo.bank.MBankEleValidateVO;
import com.sx.model.manage.mybatis.vo.company.MCompanyImportConsumerInfoVO;
import com.sx.model.manage.mybatis.vo.consumer.MPersonalConsumerNetworkVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.sys.MSysConfigVO;
import com.sx.model.util.StringsUtil;

/**
 * 公司导入用户信息 web service
 * 
 * @author lenovo
 *
 */
@Service("consumerCompanyWebServiceImpl")
@Transactional(propagation = Propagation.REQUIRED)
public class MConsumerCompanyWebServiceImpl {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Resource(name = "companyImportConsumerInfoServiceImpl")
	private IMcompanyImportConsumerInfoService companyImportConsumerInfoServiceImpl;

	// 用户信息新接口
	@Resource(name = "mNetworkPersonConsumerBizImpl")
	public IMNetworkPersonConsumerBiz mNetworkPersonConsumerBizImpl;
	// 系统参数配置
	@Resource(name = "mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;
	// 用户基本信息
	@Resource(name = "mBasePersonConsumerNetworkServiceImpl")
	private IMBasePersonConsumerNetworkService mBasePersonConsumerNetworkServiceImpl;
	// 用户扩展信息
	@Resource(name = "consumerOperationInfoServiceImpl")
	private IMConsumerOperationInfoService consumerOperationInfoServiceImpl;
	//帮助类
	@Resource(name="consumerWebServiceUtil")
	private MConsumerWebServiceUtil consumerWebServiceUtil;

	public IMcompanyImportConsumerInfoService getCompanyImportConsumerInfoServiceImpl() {
		return companyImportConsumerInfoServiceImpl;
	}

	public void setCompanyImportConsumerInfoServiceImpl(IMcompanyImportConsumerInfoService companyImportConsumerInfoServiceImpl) {
		this.companyImportConsumerInfoServiceImpl = companyImportConsumerInfoServiceImpl;
	}

	public IMNetworkPersonConsumerBiz getmNetworkPersonConsumerBizImpl() {
		return mNetworkPersonConsumerBizImpl;
	}

	public void setmNetworkPersonConsumerBizImpl(IMNetworkPersonConsumerBiz mNetworkPersonConsumerBizImpl) {
		this.mNetworkPersonConsumerBizImpl = mNetworkPersonConsumerBizImpl;
	}

	public IMBaseSystemConfigInfoService getmBaseSystemConfigInfoServiceImpl() {
		return mBaseSystemConfigInfoServiceImpl;
	}

	public void setmBaseSystemConfigInfoServiceImpl(IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl) {
		this.mBaseSystemConfigInfoServiceImpl = mBaseSystemConfigInfoServiceImpl;
	}

	public IMBasePersonConsumerNetworkService getmBasePersonConsumerNetworkServiceImpl() {
		return mBasePersonConsumerNetworkServiceImpl;
	}

	public void setmBasePersonConsumerNetworkServiceImpl(IMBasePersonConsumerNetworkService mBasePersonConsumerNetworkServiceImpl) {
		this.mBasePersonConsumerNetworkServiceImpl = mBasePersonConsumerNetworkServiceImpl;
	}

	/**
	 * 修改三要素信息
	 * 
	 * @param consumer_ids
	 * @param loginConsumer
	 * @return
	 */
	public ResultBooleanVO edit_validate_batch(Long[] consumer_ids, MConsumerLoginVO loginConsumer) {
		ResultBooleanVO result = null;
		log.info("三要素验证consumer_ids={}", NumberUtil.arrayToStr(consumer_ids));
		result = companyImportConsumerInfoServiceImpl.edit_validate_batch(consumer_ids, loginConsumer);
		// 没有通过人工验证
		if (!result.isSuccess()) {
			return result;
		}
		StringBuilder errorStr = new StringBuilder();
		// 通过人工验证
		List<MCompanyImportConsumerInfoVO> resultList = this.companyImportConsumerInfoServiceImpl.get_consumer_byIds(consumer_ids).getData();
		resultList.forEach(consumer -> {
			// 添加到正式库
			consumer.setKey_validate(MUserInfoBankValidate.VALIDATE_SUCCESS);
			MPersonalConsumerNetworkVO networkVO = validateConsumerIsExists(consumer);

			ResultBooleanVO insertResult = null;
			if (null == networkVO) {//身份账号不重复
				insertResult = mNetworkPersonConsumerBizImpl.company_import_add_consumer(this.createPerConsumerPO(consumer), loginConsumer);
			} else {//身份证号重复
				//数据入库前的验证，解绑出金卡等操作
				insertResult = consumerWebServiceUtil.excelImportRelieveBank(networkVO,consumer,loginConsumer);
				if(insertResult.isSuccess()) {
					//数据入库
					insertResult = mNetworkPersonConsumerBizImpl.excelImportEntryCompany(networkVO,consumer);
				}else {
					errorStr.append(insertResult.getMsg());	
				}
			}
			if (insertResult.isSuccess()) {
				ResultBooleanVO deleteResult = this.companyImportConsumerInfoServiceImpl.delete_by_id(new Long[] { consumer.getId() }, loginConsumer);
				if (!deleteResult.isSuccess()) {
					if (errorStr.length() > 0) {
						errorStr.append(",").append(consumer.getConsumer_name()).append(insertResult.getMsg());
					} else {
						errorStr.append(consumer.getConsumer_name()).append(insertResult.getMsg());
					}
				}
			} else {
				if (errorStr.length() > 0) {
					errorStr.append(",").append(consumer.getConsumer_name()).append(insertResult.getMsg());
				} else {
					errorStr.append(consumer.getConsumer_name()).append(insertResult.getMsg());
				}
			}
		});
		if (errorStr.length() > 0) {
			result = new ResultBooleanVO(false, null, errorStr.toString());
		}
		return result;
	}

	/**
	 * 用户三要素信息验证(新的华夏接口)
	 * 
	 * @param consumer_id
	 * @return
	 */
	public ResultBooleanVO threeElements(Long[] consumer_ids, MConsumerLoginVO loginConsumer) {
		if (null == consumer_ids) {
			return new ResultBooleanVO("m.parameter.is.null");
		}
		this.log.error("开始调用三要素验证，需要验证的用户consumer_ids：", NumberUtil.arrayToStr(consumer_ids));
		ResultBooleanVO result = null;
		List<MCompanyImportConsumerInfoVO> resultList = this.companyImportConsumerInfoServiceImpl.get_consumer_byIds(consumer_ids).getData();
		if (null == resultList) {
			return new ResultBooleanVO(false, "m.user.not.exist", null);
		}
		StringBuilder error = new StringBuilder();
		// 三要素验证功能状态
		boolean bankThreeElementsStatus = false;

		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
		form.setConfig_name(MSystemConstants.BANK_THREE_ELEMENTS_STATUS);
		ResultObjectVO<MSysConfigVO> objResult = this.mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form);
		// 获取查询的数据
		MSysConfigVO systemConfigVO = objResult.getObjVo();
		log.error("开始调用MCIP的三要素验证接口");
		String value = systemConfigVO.getConfig_value();
		// 根据配置开判断
		if (MSystemConstants.AUTO_TAKE_MONEY_YES.equalsIgnoreCase(value)) {
			bankThreeElementsStatus = true;
		}
		String str = null;
		// 华夏三要素验证
		MBankEleValidateVO bankValidateVO = null;
		for (MCompanyImportConsumerInfoVO consumer : resultList) {
			log.info("需要验证的用户数据consumer={}",consumer);
			if (!MSystemConstants.NATIONALITY_CHINA_.equals(consumer.getNationality())) {
				log.error(consumer.getConsumer_name() + ":不是中国大陆身份证用户，请使用其它鉴权方式");
				error.append(consumer.getConsumer_name() + ":不是中国大陆身份证用户，请使用其它鉴权方式");
				continue;
			}
			if (!MSystemConstants.CREDENTIALS_IDENTITYCARD.equals(consumer.getLaw_type()) && !MSystemConstants.CREDENTIALS_IDENTITYCARD_STR.equals(consumer.getLaw_type())) {
				log.error(consumer.getConsumer_name() + ":证件类型不是身份证，请使用其它鉴权方式");
				error.append(consumer.getConsumer_name() + ":证件类型不是身份证，请使用其它鉴权方式");
				continue;
			}
			this.log.error("三要素验证数据封装：");
			bankValidateVO = new MBankEleValidateVO();
			bankValidateVO.setBankNo(consumer.getCard_num());
			bankValidateVO.setBank_no(consumer.getCard_num());
			bankValidateVO.setIdNo(consumer.getLaw_no());
			bankValidateVO.setId_no(consumer.getLaw_no());
			bankValidateVO.setName(consumer.getConsumer_name());
			log.error("正式调用三要素验证:" + JackJsonUtil.objToJson(bankValidateVO));
			//{"name":"郭再兴","idNo":"211021199008122938","id_no":null,"bankNo":"6212263301015796872","bank_no":null,"authType":"01","phone":null}
			if (bankThreeElementsStatus) {
				str = mNetworkPersonConsumerBizImpl.bank_three_elements(bankValidateVO);
			} else {
				log.info("三要素验证状态未开启，默认成功{}", bankValidateVO);
				str = "{success:true}";
			}
			if (StringUtils.isBlank(str)) {
				return new ResultBooleanVO(false, null, "调用华夏鉴权结果异常，终止操作");
			}
			ResultBooleanVO insertResult = null;
			try {
				// 解析三要素验证信息
				JSONObject jsonObj = new JSONObject(str);
				// 验证通过
				if ((boolean) jsonObj.get("success")) {
					// 验证通过添加到正式库
					consumer.setKey_validate(MUserInfoBankValidate.VALIDATE_SUCCESS);
					MPersonalConsumerNetworkVO networkVO = validateConsumerIsExists(consumer);
					if (null == networkVO) {//身份账号不重复
						insertResult = mNetworkPersonConsumerBizImpl.company_import_add_consumer(this.createPerConsumerPO(consumer), loginConsumer);
					} else {//身份证号重复
						//数据入库前的验证，解绑出金卡等操作
						insertResult = consumerWebServiceUtil.excelImportRelieveBank(networkVO,consumer,loginConsumer);
						if(insertResult.isSuccess()) {
							//数据入库
							insertResult = mNetworkPersonConsumerBizImpl.excelImportEntryCompany(networkVO,consumer);
						}else {
							error.append(insertResult.getMsg());	
						}
						//insertResult = mNetworkPersonConsumerBizImpl.excelImportEntryCompany(networkVO,consumer);
					}
					if (insertResult.isSuccess()) {
						ResultBooleanVO deleteResult = this.companyImportConsumerInfoServiceImpl.delete_by_id(new Long[] { consumer.getId() }, loginConsumer);
						if (!deleteResult.isSuccess()) {
							log.debug("删除公司导入数据时失败，抛出异常事物回滚");
							throw new MRollbackException("操作失败");
						}
					} else {
						error.append(consumer.getConsumer_name()).append(insertResult.getMsg());
					}
					log.debug("正式入库时出错：" + insertResult.getMsg());
					consumer.setImport_status(MCompanyConsumersImportStatus.VALIDATE_NOT_PASS);
					companyImportConsumerInfoServiceImpl.edit_validate(consumer.getId(), MUserInfoBankValidate.VALIDATE_FAILURE, insertResult.getMsg(), loginConsumer);
					companyImportConsumerInfoServiceImpl.edit_status(MCompanyConsumersImportStatus.VALIDATE_NOT_PASS, new Long[] { consumer.getId() }, null);

				} else {// 验证不通过
					consumer.setImport_status(MCompanyConsumersImportStatus.VALIDATE_NOT_PASS);
					companyImportConsumerInfoServiceImpl.edit_validate(consumer.getId(), MUserInfoBankValidate.VALIDATE_FAILURE, null, loginConsumer);
					companyImportConsumerInfoServiceImpl.edit_status(MCompanyConsumersImportStatus.VALIDATE_NOT_PASS, new Long[] { consumer.getId() }, null);
				}
				//
				log.info("开始封装给界面返回的数据");
				str = StringsUtil.validateJsonToStr(consumer.getConsumer_name(), str);
				if (StringUtils.isNotBlank(str)) {
					error.append(str);
				}
			} catch (Exception e) {
				log.error("开户异常error={},consumer={}", e, consumer);
				return new ResultBooleanVO("m.user.three.elements.validate.error");
			}
		}

		if (error.length() > 0) {
			result = new ResultBooleanVO(false, "m.user.three.elements.validate.error", error.toString());
			return result;
		}
		result = new ResultBooleanVO();
		return result;
	}

	/** 生成个人用户信息添加使用 **/
	private MPersonalConsumerNetworkForm createPerConsumerPO(MCompanyImportConsumerInfoVO vo) {
		MPersonalConsumerNetworkForm returnForm = new MPersonalConsumerNetworkForm();
		try {
			BeanUtils.copyProperties(vo, returnForm, false);
			returnForm.setLaw_type(MPaperTypeUtil.str2PapersType(vo.getLaw_type()));

			returnForm.setCity_id(vo.getCity_id());
			returnForm.setBank_id(vo.getBank_id());
			returnForm.setCls_bank_code(vo.getCls_bank_code());
			returnForm.setCls_bank_name(vo.getCls_bank_name());
			returnForm.setCard_num(vo.getCard_num());
			returnForm.setBank_consumer_name(vo.getBank_consumer_name());

		} catch (Exception ex) {
			log.error("生成个人用户信息添加使用 error={}", ex);
			log.error(" MCompanyImportConsumerInfoVO to MPersonalConsumerInfoEntityPO 出错={}", ex.getMessage());
		}
		return returnForm;
	}

	/**
	 * 5 查询分页
	 * 
	 * @param form
	 */
	public ResultListVO<MCompanyImportConsumerInfoVO> query_page(MCompanyImportConsumerInfoForm form) {
		if (null == form) {
			return new ResultListVO<>("m.parameter.is.null");
		}
		if (null == form.getImport_status()) {
			form.setImport_status(MCompanyConsumersImportStatus.PLATFORM_AUDIT);
		}
		return companyImportConsumerInfoServiceImpl.query_page(form);
	}

	/** 验证需要导入的用户是否已经存在 **/
	public MPersonalConsumerNetworkVO validateConsumerIsExists(MCompanyImportConsumerInfoVO importConsumerVO) {
		/// 查询的 身份证号参数
		List<String> lawNoList = new ArrayList<>();
		lawNoList.add(importConsumerVO.getLaw_no());
		// 查询重复数据
		List<MPersonalConsumerNetworkVO> perConsumerList = this.mBasePersonConsumerNetworkServiceImpl.queryListByLawNo(lawNoList).getData();
		if (!perConsumerList.isEmpty()) {
			return perConsumerList.get(0);
		}
		return null;
	}
}
